//
//  HMNetwork.m
//  仿真开发
//
//  Created by jieChen on 17/3/23.
//  Copyright © 2017年 B.HOPE. All rights reserved.
//

#import "HMNetwork.h"

@implementation HMNetwork

+ (instancetype) sharedTool {
    static HMNetwork *tool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool = [[HMNetwork alloc] initWithBaseURL:nil];
    });
    return tool;
}

- (void)reqeustWithURL: (NSString *)url method:(NSString *)method parameters:(NSDictionary *)parameters callBack:(void (^)(id response)) callBack {
    
    // 调用AFN发起GET请求
    if ([method isEqualToString:@"GET"]) {
        [self GET:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            callBack(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
            callBack(nil);
        }];
    }
    
    if ([method isEqualToString:@"POST"]) {
        [self POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            callBack(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
            callBack(nil);
        }];
    }
}

- (void)POSTWithURLString:(NSString *)URLString parameters:(id)parameters success:(void(^)(id responseObject))success faile:(void(^)(NSError *error))faile{
    [self POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // AFN的回调,默认就是在主线程
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (faile) {
            faile(error);
        }
    }];
}

@end
